package com.client.action;

import com.client.service.UserInfoClientService;
import com.data.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 用户信息管理
 *
 * @author:HingLo
 * @create 2017-10-12 9:14
 **/

@Controller()
@RequestMapping("userInfoClient/client/")
public class UserInfoClientAction {
    private static Logger logger = Logger.getLogger(UserInfoClientAction.class);


    @Autowired
    private UserInfoClientService userInfoClientService;


    /***
     * 检测邮箱是否被占用
     * @param username 传入的可以是用户名，或者是邮箱，手机号
     * @param request request
     * @return 如果邮箱检验成功，就发送一封验证码的邮件，否则就直接返回json格式的提示信息
     */
    @RequestMapping("/checkEmail")
    @ResponseBody
    public Map<String, Object> checkEmailAction(@RequestParam("username") String username, HttpServletRequest request) {
        boolean bool = userInfoClientService.checkEmailService(username);
        if (bool) {
            return sendUserEmailAction(request, username);
        }
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, "邮箱已经被占用,请直接登录或者更换邮箱"));
    }

    /**
     * 发送邮件
     *
     * @param request request
     * @param email   发送的验证码的邮箱地址
     * @return 返回提示信息，如果发送成功，就返回成功，否则直接返回失败的提示信息
     */
    @PostMapping("sendUserEmail")
    @ResponseBody
    public Map<String, Object> sendUserEmailAction(HttpServletRequest request, @RequestParam("email") String email) {
        boolean bool = isBool(email, request);
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "send success!" : "send fail!"));
    }


    /**
     * 检测邮箱验证码是或否正确
     *
     * @param request
     * @param code    被检测的验证码
     * @return 返回json格式的提示
     */
    @RequestMapping("checkEmailCode")
    @ResponseBody
    public Map<String, Object> chenkEmailCodeAction(HttpServletRequest request, @RequestParam("code") String code) {

        boolean bool = false;
        if (CheckDataUtils.stringUtils(code)) {
            code = code.trim();
            String ucode = (String) request.getSession().getAttribute("code");
            if (CheckDataUtils.stringUtils(ucode)) {
                bool = code.toUpperCase().equals(ucode.toLowerCase());
                request.getSession().removeAttribute("code");
            }

        }
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "验证码正确!" : "code invalid!"));
    }

    /**
     * 注册
     *
     * @param request
     * @param username
     * @param password
     * @return
     */
    @PostMapping("register")
    @ResponseBody
    public Map<String, Object> userRegiesterAction(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password) {
        boolean bool = CheckDataUtils.stringUtils(username, password);
        if (bool) {
            String id = DatabaseIdUtils.getDataId();
            bool = userInfoClientService.userRegiesterService(id, username, password);

        }
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "注册成功" : "注册失败，请稍后重试"));
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public Map<String, Object> userLoginAction(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) {
        boolean bool = CheckDataUtils.stringUtils(username, password);
        if (bool) {
            //加密加密在加密
            return getMassage(username, password, request);
        }
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, "用户名或密码错误"));
    }

    /**
     * 二次登录
     *
     * @param request
     * @return
     */
    @RequestMapping("logins")
    @ResponseBody
    public Map<String, Object> userLoginAction(HttpServletRequest request) {
        Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute("login");
        //返回成功后，想信息从回话中移除，保证安全
        request.getSession().removeAttribute("login");
        return map;

    }

    /**
     * 修改信息
     *
     * @param id
     * @param value
     * @param type
     * @return
     */
    @PostMapping("updateUserInfo")
    @ResponseBody
    public Map<String, Object> updateUserInfoAction(@RequestParam("id") String id, @RequestParam("value") String value, @RequestParam("type") int type) {
        try {
            value = value.trim();
            boolean bool = userInfoClientService.updateUserInfoService(id, value, type);
            return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "信息更新成功" : "信息更新失败"));
        } catch (NullPointerException e) {
            return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(false, "信息更新失败"));
        }
    }


    /**
     * 更新头像
     *
     * @param id
     * @param value
     * @param type
     * @return
     */
    @PostMapping("uploadHeader")
    @ResponseBody
    public Map<String, Object> updateUserInfoHeaderAction(@RequestParam("value") CommonsMultipartFile value, @RequestParam("id") String id, @RequestParam("type") int type) {

        boolean bool = userInfoClientService.updateUserInfoService(id, value, type);
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "头像更换成功" : "头像更换失败"));
    }

    /**
     * 修改密码
     *
     * @param id
     * @param password
     * @return
     */
    @PostMapping("changePassword")
    @ResponseBody
    public Map<String, Object> updateUserInfoPasswordAction(@RequestParam("id") String id, @RequestParam("password") String password) {
        boolean bool = userInfoClientService.updateUserInfoPasswordService(id, password);
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "password change success!" : "password change fail!"));

    }

    /**
     * @param id
     * @param token
     * @return
     * @RequestParam("newPassword") String newPassword
     * 校验token
     */
    @RequestMapping("chenkUserInfoToken")
    @ResponseBody
    public Map<String, Object> chenkUserInfoTokenAction(@RequestParam("id") String id, @RequestParam("token") String token) {
        boolean bool = userInfoClientService.chenkUserInfoTokenService(id, token);
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "token right" : "token invalid"));
    }

    /**
     * 通过账号的id与token来返回账号的信息
     *
     * @param id    账号id
     * @param token 客户端的token
     * @return 返回账号的信息
     */
    @RequestMapping("lookUserInfoToken")
    @ResponseBody
    public Map<String, Object> lookUserInfoTokenAction(@RequestParam("id") String id, @RequestParam("token") String token, HttpServletRequest request) {
        if (userInfoClientService.chenkUserInfoTokenService(id, token)) {
            List<?> list = userInfoClientService.lookUserInfoTokenService(id, token);
            if (!list.isEmpty()) {
                String value[] = {"id", "username", "email", "sex", "token", "date"};
                String url = JsonUtils.getBasePath(request) + "/userInfoClient/client/lookHeader?id=";
                return SoftwareMassageUtils.getSoftwareMassageUtils(list, request, url, value);
            }
        }

        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(false, "账号已经失效，请重新登录"));
    }


    /**
     * 通过用户名与密码返回信息
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    private Map<String, Object> getMassage(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) {
        List<?> list = userInfoClientService.userLoginService(username, password);
        boolean bool = !list.isEmpty();
        if (bool) {
            String value[] = {"id", "username", "email", "sex", "token", "date"};
            String url = JsonUtils.getBasePath(request) + "/userInfoClient/client/lookHeader?id=";
            request.getSession().setAttribute("login", SoftwareMassageUtils.getSoftwareMassageUtils(list, request, url, value));
        }
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "登录成功" : "账号或者密码错误"));
    }

    /**
     * 查看头像
     *
     * @param id
     * @param response
     */

    @GetMapping("lookHeader")
    public void lookUserInfoHeaderAction(@RequestParam("id") String id, HttpServletResponse response) {
        logger.debug("..................................." + id);
        byte[] inputStream = userInfoClientService.lookUserInfoHeaderService(id);
        ImageLookUtils.responseImage(inputStream, response);
    }

    /**
     * 忘记密码密码后，通过邮箱来找回密码
     *
     * @param email
     * @param request
     * @return
     */
    @RequestMapping("forgetPasswordCheckEmail")
    @ResponseBody
    public Map<String, Object> forgetPasswordCheckEmailAction(@RequestParam("email") String email, HttpServletRequest request) {
        boolean bool = userInfoClientService.forgetPasswordCheckEmailService(email);
        if (bool) {
            bool = isBool(email, request);
        }
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "邮箱正确,请输入验证码" : "该邮箱不存在"));
    }


    /**
     * 重置密码
     *
     * @param email
     * @param password
     * @param newpassword
     * @return
     */
    @RequestMapping("settingPassword")
    @ResponseBody
    public Map<String, Object> settingPasswordAction(@RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("newpassword") String newpassword) {
        boolean bool = false;
        if (CheckDataUtils.stringUtils(email, password, newpassword) && password.equals(newpassword)) {
            bool = userInfoClientService.settingPasswordService(email, password);
        }
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "密码重置成功" : "填写的信息不正确"));
    }

    /**
     * 三方登录
     *
     * @param uid
     * @param token
     * @return
     */
    @PostMapping("otherLogin")
    @ResponseBody
    public Map<String, Object> otherLoginAction(@RequestParam("uid") String uid, @RequestParam("token") String token) {
        boolean bool = userInfoClientService.otherLoginService(uid, token);
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "加入成功" : "加入失败"));
    }

    /**
     * 退出登录
     *
     * @param uid
     * @return
     */
    @PostMapping("loginOut")
    @ResponseBody
    public Map<String, Object> loginOutAction(@RequestParam("uid") String uid) {
        boolean bool = userInfoClientService.loginOutService(uid);
        return JsonUtils.returnMassageUtils(true, JsonUtils.returnMassageUtils(bool, bool ? "退出成功" : "退出失败"));
    }


    /**
     * 发送邮箱验证码
     *
     * @param email
     * @param request
     * @return
     */
    private boolean isBool(@RequestParam("email") String email, HttpServletRequest request) {
        boolean bool;
        int length = 6;
        String code = VerificationCodeUtil.getAuthCode(length);
        logger.debug("你的验证码：" + code);
        bool = SendMailUtils.sendEmailCode(email, code);
        if (bool) {
            request.getSession().setAttribute("code", code);
        }

        return bool;
    }


}
